import * as THREE from 'three'
import imageUrl from '../../imgs/iocn.svg'
const createTextSprite = (text, color, callback) => {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const padding = 10
  const fontSize = 18
  const letterSpacing = 1
  const devicePixelRatio = window.devicePixelRatio || 1
  const imageAspectRatio = 147.5 / 54.5
  // Measure text width
  ctx.font = `${fontSize}px Arial`
  const textWidth = ctx.measureText(text).width
  const minLogicalWidth = textWidth + padding * 2 + letterSpacing * (text.length - 1)
  const minLogicalHeight = fontSize + padding * 2
  // Calculate canvas size
  // const logicalWidth = textWidth + padding * 2 + letterSpacing * (text.length - 1);
  // const logicalHeight = fontSize + padding * 2;
  let logicalWidth = minLogicalWidth
  let logicalHeight = minLogicalWidth / imageAspectRatio
  if (logicalHeight < minLogicalHeight) {
    logicalHeight = minLogicalHeight
    logicalWidth = logicalHeight * imageAspectRatio
  }

  // Set canvas sizes
  canvas.style.width = `${logicalWidth}px`
  canvas.style.height = `${logicalHeight}px`
  canvas.width = logicalWidth * devicePixelRatio
  canvas.height = logicalHeight * devicePixelRatio
  // Scale context for high DPI
  ctx.scale(devicePixelRatio, devicePixelRatio)
  ctx.font = `${fontSize}px Arial`

  // Load image and create sprite when ready
  const img = new Image()
  img.onload = () => {
    ctx.clearRect(0, 0, logicalWidth, logicalHeight)
    const imgWidth = logicalWidth
    const imgHeight = imgWidth / imageAspectRatio
    const yOffset = Math.max(0, (logicalHeight - imgHeight) / 2)
    ctx.drawImage(img, 0, yOffset, imgWidth, imgHeight)
    // Draw text
    ctx.fillStyle = color
    ctx.textBaseline = 'middle'
    ctx.textAlign = 'center'
    drawTextWithLetterSpacing(ctx, text, 80, logicalHeight / 2, letterSpacing)
    // Create texture and material
    const texture = new THREE.CanvasTexture(canvas)
    const material = new THREE.SpriteMaterial({ map: texture })
    const sprite = new THREE.Sprite(material)
    // Return through callback
    callback({
      sprite: sprite,
      width: canvas.width / devicePixelRatio, // Return logical size
      height: canvas.height / devicePixelRatio
    })
  }

  img.src = imageUrl
}
// 加载纹理
const loadTexture = (url) => {
  return new Promise((resolve, reject) => {
    const texLoader = new THREE.TextureLoader()
    texLoader.load(url, resolve, undefined, reject)
  })
}
// 添加文字 Sprite
// 添加文字 Sprite
export const addTextSprite = async (scene, iconId, text = '我是标签', color = '#fff') => {
  try {
    return new Promise((resolve) => {
      createTextSprite(text, color, ({ sprite, width, height }) => {
        const obj = scene.getObjectByName(iconId)
        if (!obj) {
          console.error(`未找到名为 ${iconId} 的对象`)
          resolve({ sprite: null, obj: null })
          return
        }
        obj.children.forEach((item) => {
          if (item.type === 'Mesh') {
            sprite.position.copy(item.position)
            item.visible = false
          }
        })

        sprite.scale.set(width / 10, height / 10, 1) // Z-scale should be at least 1
        obj.add(sprite)
        resolve({ sprite, obj })
      })
    })
  } catch (error) {
    console.error('创建文字 Sprite 失败:', error)
    return { sprite: null, obj: null }
  }
}
// 添加图片 Sprite
export const addImageSprite = async (scene, iconId, itemName, imgUrl = imageUrl, scale = 5) => {
  try {
    const texture = await loadTexture(imgUrl)
    // Wait for the texture to load so we can get its dimensions
    await new Promise((resolve) => {
      if (texture.image) {
        resolve()
      } else {
        texture.onLoad = resolve
      }
    })
    // Get the image's natural dimensions
    const image = texture.image
    const width = image.width
    const height = image.height
    const aspectRatio = width / height
    const spriteMaterial = new THREE.SpriteMaterial({ map: texture })
    const sprite = new THREE.Sprite(spriteMaterial)
    // Set scale maintaining aspect ratio (height will be 'scale', width will adjust)
    sprite.scale.set(scale * aspectRatio, scale, 1)
    const obj = scene.getObjectByName(iconId)
    if (!obj) {
      console.error(`未找到名为 ${iconId} 的对象`)
      return { sprite: null, obj: null }
    }
    obj.children.forEach((item) => {
      if (item.type === 'Mesh') {
        sprite.position.copy(item.position)
        item.visible = false
      }
    })
    obj.add(sprite)
    return { sprite, obj }
  } catch (error) {
    console.error('加载图片 Sprite 失败:', error)
    throw error // Re-throw the error after logging
  }
}

function drawTextWithLetterSpacing(context, text, x, y, letterSpacing) {
  // 遍历字符串中的每个字符
  for (let i = 0; i < text.length; i++) {
    // 绘制当前字符
    context.fillText(text[i], x, y)
    // 计算下一个字符的起始位置
    // 获取当前字符的宽度（通过 measureText 方法）
    const metrics = context.measureText(text[i])
    const width = metrics.width
    // 更新 x 坐标，加上字符宽度和间距
    x += width + letterSpacing
  }
}
